import express from 'express';
import xlsx from 'node-xlsx';
import { addSql, countSql, detailSql, getResult, likeSql } from '../../../util/operateSql.js';
import { avatarUpload } from '../upload/config.js';
var router = express.Router()

const TABLE = 'robot.files'
const SPU_TABLE = 'activity_master.t_spu'
const SingleFileFileds = 'file'

router.get('/list',async (req,res,next) => {
  const sql = likeSql(TABLE,{originalname: req.query.originalname || '',...req.query},'like')  
  const row = await getResult(sql)
  const sqlCount = countSql(TABLE,{...req.query,orderBy:'post_hot'},'like')
  const count = await getResult(sqlCount)
  res.json(req.app.locals.success({list: row,total: count[0].count}))
})


router.get('/detail',async (req,res,next) => {
  const sql = detailSql(TABLE,{id:req.query.id})
  const row = await getResult(sql)
  res.json(req.app.locals.success(row))
})

router.post('/download',(req,res,next) => {
  const {fileName}  = req.body
  const sql = detailSql(TABLE)
  getResult(sql).then((result) => {
    
  }).catch((err) => {
    
  });
})

router.post('/parseExcel',avatarUpload,async (req,res,next) => {
  const file = req[SingleFileFileds]
  const workSheetFile = xlsx.parse(file.path)
  let arrData = workSheetFile[0].data
  const head = arrData.slice(0,1)
  const data = arrData.slice(1)
  const bodyData = data.map(col => {
    return {
      title: col[2],
      sub_title: col[3],
      price: col[1],
      category_id: 17,
      saleable: 1,
      valid: 1
    }
  })
  const sql = addSql(SPU_TABLE,bodyData)
  
  getResult(sql).then((result) => {
    res.json(req.app.locals.success('导入成功'))
  }).catch(e => {
    
    res.json(req.app.locals.error(e.message))
  })
})


export default router